package com.visikard.ui.activity;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Message;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import com.visikard.application.Constant;
import com.visikard.application.UIMessage;
import com.visikard.asynctask.BaseTask;
import com.visikard.asynctask.ForgotPassTask;
import com.visikard.asynctask.LoginTask;
import com.visikard.system.Theme;
import com.visikard.ui.R;
import com.visikard.utility.Utils;

public class VKLoginActivity extends BaseFragmentActivity implements OnClickListener {

	private static final int MAX_LOGION_TRY_COUNT = 5;

	//control
	private TextView txtRegister;
	private TextView txtForgotPass;
	private EditText edtUserName;
	private EditText edtPassWord;
	private EditText medtEmail = null;
	private LinearLayout lyRegisterVisikard;	

	private AlertDialog alert = null;
	
	private Context mContext;
	//count login fail time
	private int mFailCount;

	//Asynctask
	BaseTask mAsyncTask;

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			showExitDialog();
			return true;
		}
		return false;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.vk_login_activity);

		mContext = this;
		mFailCount = 0;
		innitControl();
		showKeyboard(false);		
	}

	private void innitControl() {
		lyRegisterVisikard = (LinearLayout) findViewById(R.id.layout_main_register);
		lyRegisterVisikard.setOnClickListener(this);

		txtRegister = (TextView) findViewById(R.id.vk_register);
		txtRegister.setOnClickListener(this);

		txtForgotPass = (TextView) findViewById(R.id.rg_text_forgot_pass);
		txtForgotPass.setOnClickListener(this);

		edtUserName = (EditText) findViewById(R.id.rg_edit_text_user_name);
		edtUserName.setTypeface(Theme.getFontRegular());
		edtUserName.setCursorVisible(false);
		edtUserName.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				edtUserName.setCursorVisible(true);
				// edtUserName.setFocusable(true);
				showKeyboard(true);
				return false;
			}
		});
		edtUserName
				.setOnEditorActionListener(new TextView.OnEditorActionListener() {

					@Override
					public boolean onEditorAction(TextView v, int actionId,
							KeyEvent event) {
						if (actionId == EditorInfo.IME_ACTION_NEXT) {
							edtPassWord.setCursorVisible(true);
							edtPassWord.setFocusable(true);
						}
						return false;
					}
				});

		edtPassWord = (EditText) findViewById(R.id.rg_edit_text_pass_word);
		edtPassWord.setTypeface(Theme.getFontRegular());
		edtPassWord.setCursorVisible(false);
		edtPassWord.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				edtPassWord.setCursorVisible(true);
				showKeyboard(true);
				return false;
			}
		});
		edtPassWord.setOnEditorActionListener(new OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView v, int actionId,
					KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_SEND) {
					showKeyboard(false);
					//validate userinput
					if(edtUserName.getText().toString().isEmpty()){
						Toast.makeText(VKLoginActivity.this, getString(R.string.login_field_missing_username), Toast.LENGTH_SHORT).show();
					}else if(edtPassWord.getText().toString().isEmpty()){
						Toast.makeText(VKLoginActivity.this, getString(R.string.login_field_missing_password), Toast.LENGTH_SHORT).show();
					}else{
						//start login task
						mAsyncTask = new LoginTask(mHandler);
						mAsyncTask.execute(edtUserName.getText().toString(), edtPassWord.getText().toString());						
					}
				}
				return false;
			}
		});
	}

	protected void showKeyboard(boolean show) {
		if (show)
			getWindow().setSoftInputMode(
					WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
		else
			getWindow().setSoftInputMode(
					WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
	}	
	
	/**
	 * show password recovery note
	 */
	private void showRecoveryNote() {
		String message = getResources().getString(
				R.string.login_field_invalid_1);
		if (mFailCount > 1) {
			message = getResources().getString(
					R.string.login_field_invalid_2, new Object[]{mFailCount});
		}

		AlertDialog alert = new AlertDialog.Builder(VKLoginActivity.this)
		.setIcon(android.R.drawable.ic_dialog_info)
		.setTitle(R.string.sorry_title)
		.setMessage(message)
		.setPositiveButton(R.string.button_yes,
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog,
							int which) {
						showForgotPass();
					}
				}).setNegativeButton(R.string.button_no, null)
		.create();
		
		alert.show();
	}
	
	private void showExitDialog(){
		AlertDialog dialog = new AlertDialog.Builder(this).setTitle(R.string.main_screen_dlg_exit_title)
				.setMessage(R.string.main_screen_dlg_exit_msg)
				.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						finish();
					}
				}).setNegativeButton(getString(android.R.string.no), null).create();
		dialog.show();
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case UIMessage.MSG_EMAIL_INVALID:
			alert = new AlertDialog.Builder(mContext)
					.setIcon(android.R.drawable.ic_dialog_info)
					.setTitle("Login")
					.setMessage(
							"Sorry, we need a valid email address.  Please try again")
					.setPositiveButton(android.R.string.ok,
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									showForgotPass();
								}
							})
					.setNegativeButton(android.R.string.cancel,
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									dialog.cancel();
								}
							}).create();
			break;

		case UIMessage.MSG_EXIT_APP:
			alert = new AlertDialog.Builder(mContext)
					.setIcon(android.R.drawable.ic_dialog_info)
					.setTitle("Exit")
					.setMessage("Do you want exit application")
					.setPositiveButton(android.R.string.ok,
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									VKLoginActivity.this.finish();
								}
							}).setNegativeButton(android.R.string.cancel, null)
					.create();
			break;

		}
		return alert;
	}

	private void showForgotPass() {
		Intent mIntent = new Intent(this, SendEmailRecoveryPass.class);
		if(edtUserName.getText() != null && !edtUserName.getText().toString().isEmpty()){
			mIntent.putExtra(SendEmailRecoveryPass.KEY_EMAIL, edtUserName.getText().toString());
		}
		startActivity(mIntent);
		overridePendingTransition(R.anim.anim_slide_in_from_right, R.anim.anim_slide_out_from_right);
	}

	@Override
	public void onClick(View v) {
		InputMethodManager imm;
		switch (v.getId()) {
		case R.id.vk_register:
			imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(lyRegisterVisikard.getWindowToken(), 0);

			break;
		case R.id.rg_text_forgot_pass:
			imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(lyRegisterVisikard.getWindowToken(), 0);

			showForgotPass();
			break;

		case R.id.layout_main_register:
			imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(lyRegisterVisikard.getWindowToken(), 0);
			break;

		default:
			break;
		}
	}	

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main_visikard_register_activity, menu);
		return true;
	}
	
	//Handle message method
	@SuppressWarnings("deprecation")
	@Override
	protected boolean handleMessage(Message msg){
		switch (msg.what) {
		case UIMessage.MSG_NOT_VALIDATE_EMAIL:
			Toast.makeText(
					mContext,
					"Sorry, we need a valid email address. Please try again",
					Toast.LENGTH_SHORT).show();
			medtEmail.setTextColor(Color.parseColor("#000000"));
			return true;
		case UIMessage.MSG_LOGIN_SUCCESS:			
			if (Constant.uid != -1) {
				Constant.username = edtUserName.getText().toString().trim();
				Constant.password = edtPassWord.getText().toString().trim();
				//Start Home activity
				Intent intent = new Intent(VKLoginActivity.this, MainHomeActivity.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(intent);					
				finish();
				overridePendingTransition(R.anim.push_left_in, R.anim.push_right_out);
			} else {
				if( mFailCount < MAX_LOGION_TRY_COUNT ) {
					mFailCount++;
					showRecoveryNote();
				}else{
					VKLoginActivity.this.finish();
				}
			}
			return true;
		case UIMessage.MSG_SEND_MAIL_SUCCESS:
			alert = new AlertDialog.Builder(mContext)
					.setIcon(android.R.drawable.ic_dialog_info)
					.setTitle("Login")
					.setMessage(
							"OK, we've sent the password to your email.  Please check your email, then try logging in.")
					.setPositiveButton(android.R.string.ok,
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									dialog.cancel();
								}
							}).create();
			alert.show();
			return true;
		case UIMessage.MSG_EMAIL_INVALID:
			mHandler.sendEmptyMessage(UIMessage.MSG_DISMISS_DIALOG);
			showDialog(UIMessage.MSG_EMAIL_INVALID);
			return true;
		case UIMessage.MSG_LOGIN_INCOMPLETE:
			Utils.showToast(getApplicationContext(), R.string.login_field_missing);
			return true;
		case UIMessage.MSG_WRONG_USERNAME_PASSWORD:
			showRecoveryNote();
			return true;
		}
		return super.handleMessage(msg);
	}	
}
